<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="1400px">
        <el-form ref="form" :model="model" :rules="rules" label-width="100px" v-loading="loading">
            <el-form-item label="商品名称">
                <span>{{ model.product_name }}</span>
            </el-form-item>
            <el-form-item label="商品SPU">
                <span>{{ model.spu }}</span>
            </el-form-item>
            <el-divider></el-divider>
            <el-form-item label="Color">
                <div class="el-checkbox-group">
                    <div :class="['el-checkbox', isChecked(item.id, fullColors) ? 'is-checked' : '']" @click="selectColors(item)" v-for="item in dict.colorList" :key="item.id">
                        <span :class="['el-checkbox__input', isChecked(item.id, fullColors) ? 'is-checked' : '']">
                            <span class="el-checkbox__inner"></span>
                            <input type="checkbox" class="el-checkbox__original" v-model="item.attr_name" />
                        </span>
                        <span class="el-checkbox__label">{{ item.attr_name }}</span>
                        <span class="checkbox-delete" style="padding: 0 4px" @click.stop="deleteColor(item)" v-if="item.type == 'new'"><i class="el-icon-circle-close"></i></span>
                    </div>
                    <el-input v-model="customColor" placeholder="添加自定义颜色" @blur="addColor" style="width: 200px"></el-input>
                </div>
            </el-form-item>
            <el-form-item label="Size">
                <template #label>
                    <el-select v-model="sizeModel" @change="changeSizeModel">
                        <el-option label="Size" value="size"></el-option>
                        <el-option label="letterSize" value="letterSize"></el-option>
                    </el-select>
                </template>
                <el-checkbox-group v-model="model.sizes">
                    <el-checkbox :label="item.attr_name" v-for="item in sizeList" :key="item.id"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="Cup" v-if="sizeModel === 'size'" key="sup_cup_key">
                <el-checkbox-group v-model="model.cups">
                    <el-checkbox :label="item.attr_name" v-for="item in dict.cupList" :key="item.id"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item v-for="(custom, index) in customList" :key="index">
                <template #label>
                    <el-input v-model="custom.label" @blur="getName(index)" placeholder="属性名"></el-input>
                </template>
                <div class="el-checkbox-group">
                    <div :class="['el-checkbox', isChecked(item.id, custom.fullList) ? 'is-checked' : '']" @click="selectDiameter(item)" v-for="item in custom.fullList" :key="item.id">
                        <span :class="['el-checkbox__input', isChecked(item.id, custom.fullList) ? 'is-checked' : '']">
                            <span class="el-checkbox__inner"></span>
                            <input type="checkbox" class="el-checkbox__original" v-model="item.attr_name" />
                        </span>
                        <span class="el-checkbox__label">{{ item.attr_name }}</span>
                        <span class="checkbox-delete" style="padding: 0 4px" @click.stop="deleteCustomItem(item, custom.data)"><i class="el-icon-circle-close"></i></span>
                    </div>
                    <el-input v-model="custom.value" :placeholder="`添加${custom.name || '自定义属性'}`" @blur="addCustomItem(custom.value, custom)" style="width: 200px"></el-input>
                    <span style="padding: 0 8px" @click.stop="deleteCustom(index)"><i class="el-icon-delete" style="font-size: 18px"></i></span>
                </div>
            </el-form-item>
            <el-button @click="addCustom">新增属性</el-button>
            <el-divider></el-divider>
            <el-table :data="model.variant_arr" border script v-if="model.variant_arr.length > 0">
                <el-table-column label="图片">
                    <template slot-scope="scope">
                        <ImageUploadImg v-model="scope.row.image_info" :limit="5"></ImageUploadImg>
                    </template>
                </el-table-column>
                <el-table-column label="变种属性" prop="attr_text"></el-table-column>
                <el-table-column label="商品SKU" label-class-name="table-header-required">
                    <template #header>
                        <span>商品SKU</span>
                        （
                        <!-- <span style="color: #11a983; cursor: pointer" @click="showAutoDialog">自动</span>· -->
                        <span style="color: #11a983; cursor: pointer" @click="showSeniorDialog">高级</span>）
                    </template>
                    <template slot-scope="scope">
                        <el-input v-model.trim="scope.row.seller_sku"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="平台SKU">
                    <template slot-scope="scope">
                        <el-input v-model.trim="scope.row.platform_sku" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="中文名称">
                    <template slot-scope="scope">
                        <el-input type="textarea" autosize v-model.trim="scope.row.seller_sku_cn" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="英文名称">
                    <template slot-scope="scope">
                        <el-input type="textarea" autosize v-model.trim="scope.row.seller_sku_en" placeholder="请输入"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="来源URL">
                    <template slot-scope="scope">
                        <el-input type="textarea" autosize v-model.trim="scope.row.seller_sku_url" placeholder="多个来源URL以“|”分隔"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" :loading="save" :disabled="save" @click="submit">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>

        <el-dialog title="商品SKU" :visible.sync="autoVisible" width="600px" append-to-bod>
            <el-form ref="formAuto" :model="modelAuto" label-width="100px" v-loading="loading">
                <el-form-item label="前缀">
                    <el-input v-model.trim="modelAuto.prefix" placeholder="示例：GX"></el-input>
                </el-form-item>
                <el-form-item label="后缀">
                    <el-input v-model.trim="modelAuto.suffix" placeholder="示例：US"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="autoSave">确 定</el-button>
                <el-button @click="autoVisible = false">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="SKU高级生成规则" :visible.sync="seniorVisible" width="1400px" append-to-body>
            <el-form ref="formSenior" :model="modelSenior" label-width="200px">
                <el-form-item label="第一步：设置前后缀">
                    <el-input v-model.trim="modelSenior.prefix" placeholder="示例：GX" style="width: 200px; margin-right: 16px" @input="getPreviewValue">
                        <template slot="prepend">前缀</template>
                    </el-input>
                    <el-input v-model.trim="modelSenior.character" placeholder="示例：-" style="width: 200px; margin-right: 16px" @input="getPreviewValue">
                        <template slot="prepend">连接符</template>
                    </el-input>
                    <el-input v-model.trim="modelSenior.suffix" placeholder="示例：US" style="width: 200px" @input="getPreviewValue">
                        <template slot="prepend">后缀</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="第二步：SKU顺序">
                    <el-tag size="large" v-for="(item, index) in modelSenior.attrList" :key="index" style="margin-right: 16px">{{ item.name }}</el-tag>
                </el-form-item>
                <el-form-item label="第三步：设置变种代码">
                    <el-collapse v-model="activeNames">
                        <el-collapse-item :name="item.name" v-for="(item, index) in modelSenior.attrList" :key="index">
                            <template slot="title">
                                <span style="font-size: 18px; font-weight: bold">{{ item.name }}</span>
                            </template>
                            <div style="display: flex">
                                <div v-for="(temp, tempIndex) in item.data" :key="tempIndex" style="margin: 8px 32px 8px 0">
                                    <span>{{ temp.value }}</span>
                                    <el-input v-model="temp.editValue" style="width: 200px" @input="getPreviewValue"></el-input>
                                </div>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </el-form-item>
                <el-form-item label="第四步：SKU生成预览">
                    <el-input v-model="modelSenior.previewValue"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="seniorSave">确 定</el-button>
                <el-button @click="seniorVisible = false">取 消</el-button>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
import { getDetail, getSkuAttr, addSellerSku, addColor, deleteColor } from '@/api/product'
import { SKU_COLOR, SKU_SIZE } from '../constant'
import { deepClone } from '@/utils'
export default {
    name: 'DetailDialog',
    props: {
        value: {
            type: Boolean,
            default: false,
            required: true,
        },
        params: {
            type: Object,
            default: () => {},
        },
    },
    data() {
        return {
            activeNames: 'color',
            loading: false,
            save: false,
            sizeModel: 'size',
            model: {
                product_id: '',
                product_name: '',
                spu: '',
                variant_arr: [],
                colors: [],
                sizes: [],
                cups: [],
            },
            fullColors: [],
            customList: [],
            customDefault: {
                label:'',
                name: '',
                data: [],
                fullList: [],
            },
            autoVisible: false,
            modelAuto: {
                prefix: '',
                suffix: '',
            },
            seniorVisible: false,
            modelSenior: {
                prefix: '',
                character: '',
                before_character: '',
                suffix: '',
                attrList: [],
                previewValue: '',
            },
            rules: {},
            SKU_COLOR,
            SKU_SIZE,
            dict: {
                colorList: [],
                sizeList: [],
                letterSizeList: [],
                cupList: [],
            },
            customColor: '',
        }
    },
    computed: {
        title() {
            return `SKU信息`
        },
        dialogVisible: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            },
        },
        canCalc() {
            let customData = ''
            this.customList.forEach(item=>{customData += '--' + item.data.length})
            return this.model.colors.length + '--' + this.model.sizes.length + '--' + this.model.cups.length + '--' + customData
        },
        sizeList() {
            return this.sizeModel === 'size' ? this.dict.sizeList : this.dict.letterSizeList
        },
    },
    watch: {
        params: {
            handler(val) {
                if (val) {
                    this.model.spu = val.spu
                    this.model.product_name = val.product_name
                    this.model.product_id = val.id
                }
            },
            immediate: true,
            deep: true,
        },

        canCalc: {
            handler(val) {
                this.setVariantArr()
            },
            immediate: true,
        },
    },
    async created() {
        this.loading = true
        try {
            const result = await getSkuAttr()
            const old_colors = result.data?.color?.old_color ?? []
            old_colors.map(pre => {
                pre.type = 'old'
                return { ...pre }
            })
            const new_colors = result.data?.color?.new_color ?? []
            new_colors.map(pre => {
                pre.type = 'new'
                return { ...pre }
            })
            this.dict.colorList = [].concat(old_colors).concat(new_colors)
            this.dict.sizeList = result.data?.sizes.size ?? []
            this.dict.letterSizeList = result.data?.sizes.letterSize ?? []
            this.dict.cupList = result.data?.cup ?? []
        } catch (error) {}
        this.loading = false
        // this.getDetail()
    },
    methods: {
        getName(index) {
            this.customList[index].name = this.customList[index].label.toLocaleLowerCase() 
        },
        addCustom() {
            this.customList.push(this.customDefault)
        },
        deleteCustom(index) {
            this.customList.splice(index, 1)
        },
        addCustomItem(value, item) {
            const index = item.fullList.findIndex(pre => pre.id === value)
            if (index == -1) {
                item.fullList.push({ attr_name: value, id: value })
                item.data.push(value)
            } else {
                item.fullList.splice(index, 1)
                item.data.splice(index, 1)
            }
            value = ''

            this.$forceUpdate()
        },
       
        deleteCustomItem(item, list) {
            const index = list.findIndex(pre => pre.id === item.id)
            if (index != -1) {
                list.splice(index, 1)
            }
            this.$forceUpdate()
        },
        async addColor() {
            if (!this.customColor) {
                return
            }
            this.loading = true

            const res = await addColor({ color_name: this.customColor })

            const newItem = { id: res.data.id, attr_name: res.data.color_name, type: 'new' }
            this.$message.success(res.msg)
            this.dict.colorList.push(newItem)
            this.selectColors(newItem)
            this.customColor = ''

            this.loading = false
        },
        async deleteColor(item) {
            this.loading = true
            const res = await deleteColor({ color_id: item.id })
            this.$message.success(res.msg)
            const index = this.fullColors.findIndex(pre => pre.id == item.id)
            if (index != -1) {
                this.fullColors.splice(index, 1)
                this.model.colors.splice(index, 1)
            }
            const dictIndex = this.dict.colorList.findIndex(pre => pre.id == item.id)
            if (dictIndex != -1) {
                this.dict.colorList.splice(dictIndex, 1)
            }
            this.loading = false
        },
        isChecked(id, list) {
            return list.findIndex(item => item.id === id) > -1
        },
   
        selectColors(item) {
            const index = this.fullColors.findIndex(pre => pre.id == item.id)
            if (index != -1) {
                this.fullColors.splice(index, 1)
                this.model.colors.splice(index, 1)
            } else {
                this.fullColors.push(item)
                this.model.colors.push(item.attr_name)
            }
        },
        changeSizeModel() {
            this.list.cups = []
        },
        showAutoDialog() {
            this.autoVisible = true
            this.modelAuto.prefix = ''
            this.modelAuto.suffix = ''
        },
        showSeniorDialog() {
            if (this.model.variant_arr.length == 0) {
                return this.$message.error('变种信息SKU为空，无法使用高级生成')
            }
            this.seniorVisible = true
            this.modelSenior = Object.assign(this.modelSenior, this.model.variant_arr[0])
            this.modelSenior.before_character = this.modelSenior.character
            const { colors, sizes, cups } = this.model
            let attrList = [
                {
                    name: 'color',
                    data: colors.map(pre => {
                        return { value: pre, editValue: pre }
                    }),
                },
                {
                    name: 'size',
                    data: sizes.map(pre => {
                        return { value: pre, editValue: pre }
                    }),
                },
                {
                    name: 'cup',
                    data: cups.map(pre => {
                        return { value: pre, editValue: pre }
                    }),
                },
            ]
            const customList = this.customList.map(custom=>{
                return {
                    name: custom.name,
                    data: custom.data.map(pre=>{
                        return { value: pre, editValue: pre}
                    })
                }
            })
            attrList=attrList.concat(customList)
            this.modelSenior.attrList = attrList.filter(item => item.data.length > 0)
            this.getPreviewValue()
        },
        getPreviewValue(value) {
            if (value) {
                this.$forceUpdate()
            }

            const prefix = this.modelSenior.prefix ? this.modelSenior.prefix + this.modelSenior.character : ''
            let content = ''
            this.modelSenior?.attrList?.map((item, index) => {
                if (index == 0 || item.name == 'cup') {
                    content += item.data[0].editValue
                } else {
                    content += this.modelSenior.character + item.data[0].editValue
                }
            })

            const suffix = this.modelSenior.suffix ? this.modelSenior.character + this.modelSenior.suffix : ''

            this.modelSenior.previewValue = `${prefix}${content}${suffix}`
        },
        seniorSave() {
            const attrList = this.calcDescartesUpdate()
            this.model.variant_arr.map(item => {
                const tempInfo = attrList.find(temp => temp.before_seller_sku === item.before_seller_sku) ?? {}

                item = Object.assign(item, tempInfo)
                return { ...item }
            })
            this.seniorVisible = false
        },
        setVariantArr() {
            const attrList = this.calcDescartes()
            const beforeAttrList = deepClone(this.model.variant_arr)
            this.model.variant_arr = []
            attrList.forEach(item => {
                const index = beforeAttrList.findIndex(temp => temp.before_seller_sku === item.before_seller_sku || temp.seller_sku === item.seller_sku)
                const beforeItem = beforeAttrList.find(temp => temp.before_seller_sku === item.before_seller_sku || temp.seller_sku === item.seller_sku)
                if (index == -1) {
                    this.model.variant_arr.push(item)
                } else {
                    this.model.variant_arr.push(beforeItem)
                }
            })
        },
        autoSave() {
            const { prefix, suffix } = this.modelAuto
            if (prefix || suffix) {
                this.model.variant_arr.map(pre => {
                    pre.prefix = prefix
                    pre.suffix = suffix
                    pre.seller_sku = (prefix ? prefix + pre.character : '') + pre.seller_sku + (suffix ? pre.character + suffix : '')
                    return { ...pre }
                })
            }
        },

        calcDescartes() {
            const { colors, sizes, cups } = this.model
            let result = []
            const defaultItem = {
                attr_text: '',
                seller_sku: '',
                before_seller_sku: '',
                platform_sku: '',
                seller_sku_cn: '',
                seller_sku_en: '',
                seller_sku_url: '',
                prefix: '',
                suffix: '',
                character: '-',
                color: '',
                size: '',
                cup: '',
            }
            let list = [
                { name: 'color', data: colors },
                { name: 'size', data: sizes },
                { name: 'cup', data: cups },
            ]
            const customList = this.customList.map(pre=>({
                name: pre.name,
                data: pre.data
            }))
            list = list.concat(customList)
            const filterList = list.filter(item => item.data.length > 0)
            const dataCount = filterList.length
            const formateItem = ({ item = {}, defaultItem, currentKey, currentData }) => {
                return currentData.map(value => ({
                    ...item,
                    [currentKey]: value,
                    attr_text: `${item?.attr_text ?? ''}${item.attr_text ? '*' : ''}${value}`,
                    seller_sku: `${item?.seller_sku ?? ''}${item.seller_sku && currentKey != 'cup' ? defaultItem.character : ''}${value}`,
                    before_seller_sku: `${item?.before_seller_sku ?? ''}${item.before_seller_sku && currentKey != 'cup' ? defaultItem.character : ''}${value}`,
                }))
            }
            if (dataCount == 0) {
                result = []
            } else if (dataCount == 1) {
                const currentKey = filterList[0].name
                const currentData = filterList[0].data
                result = formateItem({ defaultItem, currentKey, currentData })
            } else {
                result = filterList.reduce(
                    (accumulator, currentMap) => {
                        const currentKey = currentMap.name
                        const currentData = currentMap.data
                        return accumulator.flatMap(item => formateItem({ item, defaultItem, currentKey, currentData }))
                    },
                    [defaultItem],
                )
            }

            return result
        },
        calcDescartesUpdate() {
            const { prefix, suffix, character, before_character } = this.modelSenior
            const prefixChar = prefix ? prefix + character : ''
            const suffixChar = suffix ? character + suffix : ''

            let result = []

            const filterList = this.modelSenior.attrList.filter(item => item.data.length > 0)
            const dataCount = filterList.length

            const formateItem = ({ item = {}, currentKey, currentData }) => {
                return currentData.map(temp => ({
                    ...item,
                    character,
                    prefix,
                    suffix,
                    [currentKey]: temp.editValue,
                    seller_sku: `${item?.seller_sku ?? ''}${item.seller_sku && currentKey != 'cup' ? character : ''}${temp.editValue}`,
                    before_seller_sku: `${item?.before_seller_sku ?? ''}${item.before_seller_sku && currentKey != 'cup' ? before_character : ''}${temp.value}`,
                }))
            }
            if (dataCount == 0) {
                result = []
            } else if (dataCount == 1) {
                const currentKey = filterList[0].name
                const currentData = filterList[0].data
                result = formateItem({ currentKey, currentData })
            } else {
                result = filterList.reduce(
                    (accumulator, currentMap) => {
                        const currentKey = currentMap.name
                        const currentData = currentMap.data
                        return accumulator.flatMap(item => formateItem({ item, currentKey, currentData }))
                    },
                    [{}],
                )
            }

            result = result.map(item => ({
                ...item,
                seller_sku: `${prefixChar}${item.seller_sku}${suffixChar}`,
            }))

            return result
        },
        getDetail() {
            this.loading = true
            const params = { id: this.params.id }
            getDetail(params)
                .then(res => {
                    this.model = Object.assign({}, this.model, res.data)
                })
                .finally(() => {
                    this.loading = false
                })
        },
        submit() {
            this.$refs.form.validate(valid => {
                if (!valid) {
                    return
                }

                const params = { ...this.model }
                delete params.colors
                delete params.sizes
                delete params.cups
                if (this.save) {
                    return
                }
                this.save = true
                addSellerSku(params)
                    .then(res => {
                        this.$message.success(res.msg)
                        this.dialogVisible = false
                        this.$emit('success')
                    })
                    .finally(() => {
                        this.save = false
                    })
            })
        },
        cancel() {
            this.dialogVisible = false
        },
    },
}
</script>

<style scoped></style>
